package org.dingfugui.triple.proxy.jdk;

import org.dingfugui.triple.proxy.ProxyFactory;
import org.dingfugui.triple.proxy.ProxyHandler;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * Created by fugui.ding on 2015/6/10.
 */
public class JdkProxyFactory implements ProxyFactory {
    @Override
    public <T> T getProxy(final Class<T> cls, final ProxyHandler handler) {

        return (T) Proxy.newProxyInstance(cls.getClassLoader(), new Class[]{cls}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                if (method.getName().equals("toString") && method.getParameterCount() == 0) {
                    return cls.toString();
                }
                return handler.invoke(cls.getName(), method.getName(), method.getParameterTypes(), args);
            }
        });

    }
}

